package com.example.chapter07_client;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import com.example.chapter07_client.entity.User;
import com.example.chapter07_client.util.ToastUtil;

public class ContentWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    private CheckBox ck_married;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_write);

        // 初始化界面控件，用于输入用户信息
        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        ck_married = findViewById(R.id.ck_married);

        // 为三个按钮设置点击事件监听器，当前Activity实现了OnClickListener接口
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(this);
        findViewById(R.id.btn_read).setOnClickListener(this);
    }

    @SuppressLint("Range")
    @Override
    public void onClick(View v) {
        // 判断点击的是“保存”按钮
        if (v.getId() == R.id.btn_save) {
            // 构造要插入的用户数据（ContentValues类似Map，存储键值对）
            ContentValues values = new ContentValues();
            values.put(UserInfoContent.USER_NAME, et_name.getText().toString());
            values.put(UserInfoContent.USER_AGE, Integer.parseInt(et_age.getText().toString()));
            values.put(UserInfoContent.USER_HEIGHT, Integer.parseInt(et_height.getText().toString()));
            values.put(UserInfoContent.USER_WEIGHT, Float.parseFloat(et_weight.getText().toString()));
            values.put(UserInfoContent.USER_MARRIED, ck_married.isChecked());
            // 调用ContentResolver插入数据，Uri为服务端ContentProvider的用户表地址
            getContentResolver().insert(UserInfoContent.CONTENT_URI, values);
            ToastUtil.show(this, "保存成功");

            // 判断点击的是“读取”按钮
        } else if (v.getId() == R.id.btn_read) {
            // 调用ContentResolver查询数据，Uri指定服务端的用户表，参数为null表示查询所有列、无筛选条件
            Cursor cursor = getContentResolver().query(UserInfoContent.CONTENT_URI, null, null, null, null);
            if (cursor != null) {
                // 遍历Cursor结果集，逐行解析用户数据
                while (cursor.moveToNext()) {
                    User info = new User();
                    // 通过列名获取对应字段的值，_ID是BaseColumns接口定义的主键字段
                    info.id = cursor.getInt(cursor.getColumnIndex(UserInfoContent._ID));
                    info.name = cursor.getString(cursor.getColumnIndex(UserInfoContent.USER_NAME));
                    info.age = cursor.getInt(cursor.getColumnIndex(UserInfoContent.USER_AGE));
                    info.height = cursor.getInt(cursor.getColumnIndex(UserInfoContent.USER_HEIGHT));
                    info.weight = cursor.getFloat(cursor.getColumnIndex(UserInfoContent.USER_WEIGHT));
                    // 婚姻状态字段是整型，转换为布尔值（1表示已婚，0表示未婚）
                    info.married = cursor.getInt(cursor.getColumnIndex(UserInfoContent.USER_MARRIED)) == 1 ? true : false;
                    Log.d("ning", info.toString());
                }
                cursor.close(); // 必须关闭Cursor，否则会导致内存泄漏
            }

            // 判断点击的是“删除”按钮
        } else if (v.getId() == R.id.btn_delete) {
            // 方式1：按条件删除（删除姓名为"Jack"的用户）
            int count = getContentResolver().delete(UserInfoContent.CONTENT_URI, "name=?", new String[]{"Jack"});
            // 方式2：按ID删除（被注释，演示通过ContentUris构造带ID的Uri）
            /*Uri uri = ContentUris.withAppendedId(UserInfoContent.CONTENT_URI, 2);
            int count = getContentResolver().delete(uri, null, null);*/
            if (count > 0) {
                ToastUtil.show(this, "删除成功");
            }
        }
    }
}